//
//  Utils.m
//
//  Created by Northwan on 15/4/12.
//  Copyright (c) 2015年 All rights reserved.
//

#import "Utils.h"
#import "YSLoginCtrl.h"
#import "CustomNavigationCtrl.h"
#import "YSCartCtrl.h"
#import "YSVirtualProtocol.h"
#import "YSProductDetailCtrl.h"
#import "YSProductListCtrl.h"
#import "YSReviewsCtrl.h"
#import "YSReviews.h"
#import "YSBusinessCtrl.h"
#import "YSWebViewCtrl.h"
#import "YSContentListCtrl.h"

@implementation Utils

+(NSString *)stringWithDate:(NSDate *)date formatterStr:(NSString *)formatterStr{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formatterStr;
    return [formatter stringFromDate:date];
}
+(NSString *)string2Millisecs:(int64_t)timestamp{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MMM-dd HH:mm"];
    return [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
}
+(BOOL)isCanLoadPicture{
    if ([SystemUtil isWifi]) {
        return YES;
    }else{
        return [DefaultsHelper boolForKey:kISShowPicture];
    }
}

+(void)clearExitInfo{
    [DefaultsHelper setObject:nil forKey:kServerSecret];
    [DefaultsHelper setObject:nil forKey:kUserId];
    [DefaultsHelper setObject:nil forKey:kAppToken];
    [DefaultsHelper setObject:nil forKey:kHeadImg];
    [DefaultsHelper setObject:nil forKey:kNickName];
    [DefaultsHelper setInteger:0 forKey:kCartIndex];
}

+(void)showLoginCtrl:(UIViewController*)ctrl{
    CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[[YSLoginCtrl alloc]init]];
    [ctrl.navigationController presentViewController:nav animated:YES completion:^{}];
}

+(void)showCartCtrl:(UIViewController*)ctrl{
    CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[[YSCartCtrl alloc]init]];
     [ctrl.navigationController presentViewController:nav animated:YES completion:^{}];
}

+(NSString *)millisecs2DateString:(int64_t)timestamp{
    int64_t nowLong = [[NSDate date] timeIntervalSince1970]*1000 ;
    int64_t seconds = (nowLong - timestamp) / 1000;
    if (seconds <= 60) {
        return @"刚刚";
    } else if (seconds < 60 * 60) {
        return [NSString stringWithFormat:@"%d分钟前",(int) (seconds / 60)];
    } else if (seconds < 60 * 60 * 24) {
        return [NSString stringWithFormat:@"%d小时前",(int) (seconds / 60 / 60)];
    } else {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"MMM-dd HH:mm"];
        return [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
    }
    return nil;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+(BOOL)dealUrlWithController:(UIViewController *)controller url:(NSString *)url fromWebView:(BOOL)fromWebView{
    BOOL result = YES;
    NSString *prefixStr  = @"yueshiopen://virtual?params=";
    if([url hasPrefix:prefixStr]){
        NSRange range =  [url rangeOfString:prefixStr];
        url =  [url substringFromIndex:range.length];
        NSDictionary *params = [Utils dictionaryWithJsonString:url];
        NSLog(@"伪连接内容:%@",url);
        YSVirtualProtocol *protocol = [YSVirtualProtocol objectWithKeyValues:params];
        BaseViewController *ctrl;
        switch (protocol.linkType) {
            case YSVirtualProtocolProductDetialMode://商品详情
                ctrl = [[YSProductDetailCtrl alloc]initWithProdId:protocol.entityId.integerValue];
                break;
            case YSVirtualProtocolCategoryPageMode://分类页面
                [[NSNotificationCenter defaultCenter]postNotificationName:kToCategoryPageNortif object:nil];
                break;
            case YSVirtualProtocolCategoryProdListMode://分类商品列表
                ctrl = [[YSProductListCtrl alloc]initWithTitle:nil categoryId:protocol.entityId.integerValue type:CATEGORY_TYPE];
                break;
            case YSVirtualProtocolBrandPageMode://品牌页面
                
                break;
            case YSVirtualProtocolAppIndexMode://首页
                 [[NSNotificationCenter defaultCenter]postNotificationName:kToHomePageNortif object:@1];
                break;
            case YSVirtualProtocolAppPastIndexMode://往期
               [[NSNotificationCenter defaultCenter]postNotificationName:kToHomePageNortif object:@2];
                break;
            case YSVirtualProtocolBusinessMode://商户
                ctrl = [[YSBusinessCtrl alloc]initWithSupplierId:protocol.entityId.integerValue];
                break;
            case YSVirtualProtocolProductPoolsMode://池子列表
                ctrl = [[YSProductListCtrl alloc]initWithTitle:nil categoryId:protocol.entityId.integerValue type:POOL_TYPE];
                break;
            case YSVirtualProtocolContentsPageMode:{//内容页面
                YSReviews *review = [YSReviews new];
                [review setId:protocol.entityId.integerValue];
                [review setPostName:@"悦食家"];
                ctrl = [YSReviewsCtrl initWithReviews:review];
                break;
            }
            case YSVirtualProtocolClubMode://俱乐部
                [[NSNotificationCenter defaultCenter]postNotificationName:kToClubPageNortif object:nil];
                break;
            case YSVirtualProtocolAddCartProdMode://添加购物篮
                
                break;
            case YSVirtualProtocolBuyProdMode://立即购买
                break;
            case YSVirtualProtocolContentPoolsMode:{//内容池子
                ctrl = [[YSContentListCtrl alloc]initWithReviewsId:protocol.entityId];
                break;
            }
            default:
                break;
        }
        [controller.navigationController pushViewController:ctrl animated:YES];
        result =  NO;
    }else if([url hasPrefix:@"http"]){
        NSString *suffix = @"login=1";
        if ([url hasSuffix:suffix]) {
            if (ISLOGIN) {
                NSString *token = [DefaultsHelper stringForKey:kAppToken];
                url = [url stringByAppendingFormat:@"&token=%@", token];
            }else{
                [Utils showLoginCtrl:controller];
                return NO;
            }
        }
        
        if (!fromWebView) {
            YSWebViewCtrl *ctrl = [YSWebViewCtrl initWithUrl:url title:@""];
            [controller.navigationController pushViewController:ctrl animated:YES];
            result = NO;
        }
    }
    return result;
}

@end
